package com.tc.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Auther: tianchao
 * @Date: 2024/12/30 12:25
 * @Description:
 */
@RestController
@RequestMapping("/session")

public class SessionController {

    Logger log = LoggerFactory.getLogger(SessionController.class);


    @GetMapping("/test1")
    public String test1(HttpServletRequest request){
        HttpSession session = request.getSession(true);
        session.setAttribute("dddddd","eeeeee");
        log.info("test1=>  session: {}", session);
        return "test1";
    }

    @GetMapping("/test2")
    public String test2(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        log.info("test2=>  session: {}", session);
        return "test2";
    }

    @GetMapping("/test3")
    public String test3(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession(false);
        log.info("test3=>");
        if (request.getAttribute("ori") == null){
            try {
                request.setAttribute("ori", "/session/test3");
                request.getRequestDispatcher("/session/test4").forward(request, response);
                log.info("test3=>转发后");
            } catch (ServletException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return "RESULT-test3-ORI";
        }
        log.info("test3=> 返回");

        return "RESULT-test3";
    }
    @GetMapping("/test4")
    public String test4(HttpServletRequest request,HttpServletResponse response){
        HttpSession session = request.getSession(false);
        log.info("test4=>  session: {}", session);
        if (false){
            throw new RuntimeException("不清楚");
        }
        try {
            request.getRequestDispatcher( (String)request.getAttribute("ori")).forward(request, response);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "RESULT-test4";
    }
}
